package com.ice.base.util;

import com.ice.base.model.SysLoginModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户工具类
 */
@Component
public class UserUtil {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 得到当前登录用户
     * @return
     */
    public List<SysLoginModel> getCurrentUserFromRedis(){
        List<SysLoginModel> userMapList = (List<SysLoginModel>) redisUtil.get("userList");
        List<SysLoginModel> userList = null;
        if(!CollectionUtils.isEmpty(userMapList)){
            userList = new ArrayList<>();
            for(SysLoginModel user:userMapList){
                SysLoginModel model = new SysLoginModel();
                model.setId(user.getId());
                model.setUserName(user.getUserName());
                model.setUserNo(user.getUserNo());
                userList.add(model);
            }
        }
        return userList;
    }

    /**
     * 得到当前登录用户ID
     * @return
     */
    public String getCurrentUserIdFromRedis(){
        List<Map<String,Object>> userMap = (List<Map<String,Object>>) redisUtil.get("userList");
        String userId = "";
        if(userMap != null){
            userId = String.valueOf(userMap.get(0).get("userId"));
        }
        return userId;
    }

    /**
     * 得到当前登录用户
     * @param request
     * @return
     */
    public SysLoginModel getCurrentUser(HttpServletRequest request){
        SysLoginModel user = (SysLoginModel) request.getSession().getAttribute("user");
        return user;
    }

    /**
     * 得到当前登录用户ID
     * @param request
     * @return
     */
    public String getCurrentUserId(HttpServletRequest request){
        String userId = "";
        SysLoginModel  user = (SysLoginModel) request.getSession().getAttribute("user");
        if(user != null){
            userId = user.getId().toString();
        }
        return userId;
    }

}